import 'package:card_swiper/card_swiper.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../../models/product_ad_model.dart';
import '../../models/product_model.dart';
import '../../datas/product.dart';

class Home extends StatefulWidget {
  const Home({super.key});
  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  final ProductAdModel _productAdListModel = ProductAdModel();
  final ProductModel _productListModel = ProductModel();

  @override
  void initState() {
    super.initState();
    _productAdListModel.loadProductAds();
    _productListModel.loadProductList();
  }

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider<ProductAdModel>(
          create: (context) => _productAdListModel,
        ),
        ChangeNotifierProvider<ProductModel>(
          create: (context) => _productListModel,
        ),
      ],

      child: Scaffold(
        appBar: AppBar(title: const Text('首页')),
        body: SafeArea(
          child: SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                SizedBox(height: 150, width: double.infinity, child: _banner()),
                SizedBox(height: 4),
                _productList(),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _banner() {
    return Consumer<ProductAdModel>(
      builder: (context, value, child) {
        return Swiper(
          itemBuilder: (BuildContext context, int index) {
            return Container(
              decoration: BoxDecoration(color: Colors.grey),
              height: 200,
              width: double.infinity,
              child: Image.network(
                value.productAdList?[index].coverAddr ?? "",
                fit: BoxFit.cover,
              ),
            );
          },
          itemCount: value.productAdList?.length ?? 0,
          autoplay: true,
          pagination: const SwiperPagination(),
          control: const SwiperControl(),
        );
      },
    );
  }

  Widget _productList() {
    return Consumer<ProductModel>(
      builder: (context, productModel, child) {
        if (productModel.isLoading) {
          return Center(child: CircularProgressIndicator());
        }

        if (productModel.errorMessage != null) {
          return Center(
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: Text('加载失败: ${productModel.errorMessage}'),
            ),
          );
        }

        final products = productModel.productList?? [];
        
        if (products.isEmpty) {
          return Center(child: Text('暂无产品'));
        }

        return GridView.builder(
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2,
            childAspectRatio: 0.75,
            crossAxisSpacing: 10,
            mainAxisSpacing: 10,
          ),
          itemCount: products.length,
          itemBuilder: (context, index) {
            return _productItem(products[index]);
          },
        );
      },
    );
  }

  Widget _productItem(Product product) {
    return GestureDetector(
      onTap: () {
        Navigator.pushNamed(
          context,
          "/product_detail",
          arguments: {"product": product},
        );
      },
      child: Card(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(
              child: Image.network(
                product.coverAddr ?? '',
                fit: BoxFit.cover,
                width: double.infinity,
                errorBuilder: (context, error, stackTrace) {
                  return Container(
                    color: Colors.grey[300],
                    child: Icon(Icons.error),
                  );
                },
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    product.title ?? '未知产品',
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14),
                  ),
                  SizedBox(height: 4),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        '¥${product.price ?? 0}',
                        style: TextStyle(
                          color: Colors.red,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      Row(
                        children: [
                          Icon(Icons.star, color: Colors.orange, size: 14),
                          Text(
                            '${product.rate ?? 0}',
                            style: TextStyle(fontSize: 12),
                          ),
                        ],
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
